package jm.data.structure.leet_code;

/**
 * @Description https://leetcode-cn.com/problems/reverse-linked-list/
 * @date 2022/4/5 17:20
 */
public class _206反转链表 {
    public static void main(String[] args) {
        ListNode head = new ListNode(4,
                new ListNode(3,
                        new ListNode(2,
                                new ListNode(1))));
        ListNode listNode = reverseList(head);
        ListNode node = listNode;
        while (node != null){
            System.out.println(node.val);
            node = node.next;
        }
    }

    public static ListNode reverseList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode newHead = null;
        while (head != null){
            ListNode tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }

    static class ListNode{
        int val;
        ListNode next;
        ListNode(int x) {
            this.val = x;
            this.next = null;
        }
        ListNode(int x,ListNode next) {
            this.val = x;
            this.next = next;
        }
    }
}

